package org.jflame.captcha.creator.factory;

import org.jflame.captcha.creator.CaptchaCreator;
import org.jflame.captcha.creator.MathCaptchaCreator;
import org.jflame.captcha.creator.SimpleImageCaptchaCreator;
import org.jflame.commons.config.ConfigReader;
import org.jflame.commons.config.ConfigKey;

import java.awt.Font;

@SuppressWarnings("rawtypes")
public class MathImageCreatorFactory extends CaptchaCreatorFactory {

    /**
     * 文字生成个数
     */

    public static ConfigKey<Integer> KEY_MATH_MAX = new ConfigKey<>("captcha.math.max", 10);

    /**
     * 文字图片:是否绘制边框
     */
    public ConfigKey<Boolean> KEY_DRAW_BORDER = new ConfigKey<>(cfgKey("draw_border"), true);
    /**
     * 生成的图片宽度
     */
    public ConfigKey<Integer> KEY_WIDTH = new ConfigKey<>(cfgKey("width"), 80);
    /**
     * 生成的图片高度
     */
    public ConfigKey<Integer> KEY_HEIGTH = new ConfigKey<>(cfgKey("heigth"), 26);
    /**
     * 字体名称,如果以file:或classpath:开头表示字段文件路径
     */
    public ConfigKey<String> KEY_FONT = new ConfigKey<>(cfgKey("font"));
    /**
     * 字体尺寸
     */
    public ConfigKey<Integer> KEY_FONT_SIZE = new ConfigKey<>(cfgKey("font_size"), 18);

    @Override
    public CaptchaCreator build(ConfigReader captchaConfig) {
        MathCaptchaCreator mathCaptchaCreator = new MathCaptchaCreator(captchaConfig.getInt(KEY_MATH_MAX));
        SimpleImageCaptchaCreator<Integer> creator = new SimpleImageCaptchaCreator<>(mathCaptchaCreator);
        creator.setWidth(captchaConfig.getInt(KEY_WIDTH));
        creator.setHeight(captchaConfig.getInt(KEY_HEIGTH));
        creator.setDrawBorder(captchaConfig.getBoolean(KEY_DRAW_BORDER));
        Font font = loadFont(captchaConfig.getString(KEY_FONT), captchaConfig.getInt(KEY_FONT_SIZE));
        if (font != null) {
            creator.setDefaultFont(font);
        }
        return creator;
    }

    @Override
    public String getCaptchaType() {
        return "math_image";
    }

}
